import 'package:flutter/material.dart';

class LoadmorePage extends StatefulWidget {
  const LoadmorePage({super.key});

  @override
  State<LoadmorePage> createState() => _LoadmorePageState();
}

class _LoadmorePageState extends State<LoadmorePage> {
  int index = 0;
  final ScrollController _scrollController = ScrollController();
  List<String> rawList = ['北京','南京','杭州','上海','深圳','广州','合肥','太原','济南','南昌','乌鲁木齐','沈阳','哈尔滨','长春'];
  List<String> cityNames = ['北京','南京','杭州','上海','深圳','广州','合肥','太原','济南','南昌','乌鲁木齐','沈阳','哈尔滨','长春'];

  @override
  void initState() {
    _scrollController.addListener((){
      if(_scrollController.position.pixels == _scrollController.position.maxScrollExtent)
        _loadData();
    });
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('下拉刷新'),),
      // body: ListView(
      //   children: _buildList(),
      // ),
      body: RefreshIndicator(
          child: ListView(
            controller: _scrollController,
            children: _buildList(),
          ),
          onRefresh: _handleRefresh
      ),
    );
  }

  List<Widget> _buildList() {
    return cityNames.map((city) => _item(city)).toList();
  }

  Widget _item(String city) {
    return Container(
      height: 80,
      margin: const EdgeInsets.only(bottom: 5),
      decoration: const BoxDecoration(color: Colors.redAccent),
      child: Text(city,style: const TextStyle(color: Colors.white,fontSize: 20),),
    );
  }

  Future<void> _handleRefresh() async {
    await Future.delayed(const Duration(seconds: 2));
    setState(() {
      cityNames = cityNames.reversed.toList();
    });
  }

  void _loadData() async {
    await Future.delayed(const Duration(milliseconds: 200));
    index++;
    List<String> newList = rawList.map((e) => e = e + index.toString()).toList();
    setState(() {
      cityNames.addAll(newList);
    });
  }
}
